/*
 * Copyright (C) 2013  Richard Schilling. All rights reserved.
 * contact: coderroadie@gmail.com
 * 
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 */

package com.example.kayakpointexample;

import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Bundle;
import android.persist.PersistException;
import android.persist.op.sqlite.SQLiteCount;
import android.persist.op.sqlite.SQLiteCreate;
import android.persist.op.sqlite.SQLiteCreateStowage;
import android.persist.op.sqlite.SQLiteDestroyStowage;
import android.persist.op.sqlite.SQLiteExistsStowage;
import android.persist.op.sqlite.SQLiteGetRowId;
import android.persist.op.sqlite.SQLiteRead;
import android.persist.op.sqlite.SQLiteReadForeign;
import android.util.Log;
import android.view.Menu;

public class MainActivity extends Activity {

    @SuppressWarnings({
            "rawtypes", "unchecked"
    })
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // uncomment to trace database operations
        // Debug.startMethodTracing("kayakpoint");

        setContentView(R.layout.activity_main);
        OpenHelper helper = new OpenHelper(this, "testdb", null, 1);
        SQLiteDatabase db = helper.getWritableDatabase();

        // test ORM
        TestTable tt = new TestTable();
        tt.b = true;
        tt.Byte = Byte.MAX_VALUE;
        tt.c = 'a';
        tt.d = 0.123456789d;
        tt.f = 0.246813579f;
        tt.i = Integer.MAX_VALUE;
        tt.l = Long.MAX_VALUE;
        tt.s = "parent";
        tt.Short = 1;

        tt.testtable = new TestTable();
        tt.testtable.b = false;
        tt.testtable.Byte = Byte.MIN_VALUE;
        tt.testtable.c = 'z';
        tt.testtable.d = Double.MIN_VALUE;
        tt.testtable.f = Float.MIN_VALUE;
        tt.testtable.i = Integer.MIN_VALUE;
        tt.testtable.l = Long.MIN_VALUE;
        tt.testtable.s = "child";
        tt.testtable.Short = Short.MIN_VALUE;

        if (new SQLiteGetRowId(db, tt).call() == null) {
            Long result = new SQLiteCreate<TestTable>(db, tt).call();
            Log.i("EXAMPLE", "inserted record at row " + result);
        }

        SQLiteCount<TestTable> countOp = new SQLiteCount<TestTable>(db, TestTable.class, null);
        long count = countOp.call();
        Log.i("EXAMPLE", "There are " + count + " records in the data store.");

        SQLiteRead<TestTable> readOp = new SQLiteRead<TestTable>(
                db, TestTable.class, null);
        List<TestTable> parentResult = readOp.call();

        for (TestTable t : parentResult) {
            SQLiteReadForeign<TestTable> readForeignOp = new SQLiteReadForeign<TestTable>(db, t);
            List<Object> foreignReferencesRead = readForeignOp.call();
            Log.i("EXAMPLE", "read " + foreignReferencesRead.size() + " foreign references");
        }

        db.close();

        // uncomment to trace database operations
        // Debug.stopMethodTracing();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    private class OpenHelper extends SQLiteOpenHelper {

        public OpenHelper(Context context, String name, CursorFactory factory, int version) {
            super(context, name, factory, version);

        }

        @Override
        public void onCreate(SQLiteDatabase db) {

            /*
             * delete TestTable stowage if it exists
             */
            SQLiteExistsStowage<TestTable> testTableExistsOp = new SQLiteExistsStowage<TestTable>(
                    db,
                    TestTable.class);
            if (testTableExistsOp.call().booleanValue()) {
                SQLiteDestroyStowage<TestTable> dropOp = new SQLiteDestroyStowage<TestTable>(db,
                        TestTable.class);
                if (!dropOp.call())
                    throw new PersistException("unable to delete table for TestTable");
            }

            /*
             * delete CollectionItem stowage if it exists
             */
            SQLiteExistsStowage<CollectionItem> collectionItemExistsOp = new SQLiteExistsStowage<CollectionItem>(
                    db,
                    CollectionItem.class);

            if (collectionItemExistsOp.call().booleanValue()) {
                SQLiteDestroyStowage<CollectionItem> dropOp = new SQLiteDestroyStowage<CollectionItem>(
                        db, CollectionItem.class);
                if (!dropOp.call()) {
                    throw new PersistException("unable to delete table for CollectionItem");
                }
            }

            // create tables for a class and all classes for its fields.
            SQLiteCreateStowage.createTable(db, TestTable.class, null);
            SQLiteCreateStowage.createTable(db, CollectionItem.class, null);

        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

        }

    }

}
